package com.junan.galiao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.junan.galiao.enums.MessageCode;
import com.junan.galiao.pojo.dbo.User;
import com.junan.galiao.mapper.UserMapper;
import com.junan.galiao.pojo.dto.Message;
import com.junan.galiao.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.junan.galiao.utils.FastJsonUtil;
import com.junan.galiao.utils.JwtTokenUtil;
import com.junan.galiao.utils.RedisUtil;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author junan
 * @since 2020-04-24
 */
@Service
@SuppressWarnings("all")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final BCryptPasswordEncoder encoder;
    private final UserMapper userMapper;
    private final RedisUtil redisUtil;

    public UserServiceImpl(BCryptPasswordEncoder encoder, UserMapper userMapper, RedisUtil redisUtil) {
        this.encoder = encoder;
        this.userMapper = userMapper;
        this.redisUtil = redisUtil;
    }

    @Override
    public Message login(User user) {
        User byId = getById(user.getUserId());
        if (byId == null) {
            return new Message()
                    .code(MessageCode.FAIL.value())
                    .data("用户不存在！");
        }

        if (!encoder.matches(user.getUserPwd(), byId.getUserPwd())) {
            return new Message()
                    .code(MessageCode.FAIL.value())
                    .data("用户名或密码错误！");
        }

        // 密码正确，产生token并返回
        user.setUserPwd(null);     // 清理掉密码
        byId.setUserPwd(null);     // 清理掉密码
        String token = JwtTokenUtil.createToken(user);

        // redis 存储登录的用户的信息 (存储一天)
        redisUtil.set(token, FastJsonUtil.toJSONString(byId), 24 * 60 * 60);

        // 获取好友
        String[] friendIds = byId.getUserFriends().split(",");
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.in("user_id", friendIds);
        wrapper.select("user_id", "user_avatar", "user_nickname");
        List<User> users = userMapper.selectList(wrapper);
        byId.setFriends(users);

        return new Message().code(MessageCode.OK.value()).data(byId).token(token);
    }

    @Override
    public Message userById(Long userId, String token) {
        // 验证token
        if(checkToken(token)) {
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId);
            wrapper.select("user_id", "user_avatar", "user_nickname");
            User user = userMapper.selectOne(wrapper);
            if(user == null)
                return new Message().code(MessageCode.USER_NOT_FOUND.value()).data("该用户不存在！");

            // 用户存在，检查是否是自己的好友
            boolean isFriend = false;
            // 获取自己的好友列表
            String[] split = FastJsonUtil.parseObject(
                    (String) redisUtil.get(token), User.class)
                    .getUserFriends()
                    .split(",");
            for (String s : split) {
                if(user.getUserId().equals(Long.valueOf(s))) {
                    isFriend = true;
                    break;
                }
            }
            user.setIsFriend(isFriend);
            return new Message().code(MessageCode.OK.value()).data(user);

        }
        // token不合法
        return new Message().code(MessageCode.FAIL.value()).data("token不合法");
    }

    @Override
    public Message strangerById(Long userId, String token) {
        // 验证token
        if(checkToken(token)) {
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId);
            wrapper.select("user_id", "user_avatar", "user_nickname");
            User stranger = userMapper.selectOne(wrapper);
            if(stranger == null)
                return new Message().code(MessageCode.USER_NOT_FOUND.value()).data("该用户不存在！");

            return new Message().code(MessageCode.OK.value()).data(stranger);
        }
        // token不合法
        return new Message().code(MessageCode.FAIL.value()).data("token不合法");
    }

    @Override
    public Message addFriend(Long friendId, String token) {
        // 验证token
        if(checkToken(token)) {
            Long userId = JwtTokenUtil.userInToken(token).getUserId();
            User user = userMapper.selectById(userId);
            user.setUserFriends(user.getUserFriends() + "," + friendId);
            user.updateById();

            user.setUserPwd(null);
            // 更新缓存数据
            redisUtil.set(token, FastJsonUtil.toJSONString(user), redisUtil.getExpire(token));

            return new Message().code(MessageCode.OK.value());
        }
        // token不合法
        return new Message().code(MessageCode.FAIL.value()).data("token不合法");
    }

    /**
     * 检查token是否正常
     * @return
     */
    private boolean checkToken(String token) {
        return JwtTokenUtil.verifyToken(token);
    }

}
